package com.ca.demo.controller.sys;

import com.ca.demo.common.base.BaseCRUDController;
import com.ca.demo.common.base.BaseController;
import com.ca.demo.common.base.Response;
import com.ca.demo.model.sys.Resource;
import com.ca.demo.service.sys.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @Author XieLei
 * @Date 2017/6/22 17:46
 */
@Controller
@RequestMapping("/sys/resource")
public class ResourceController extends BaseCRUDController<Resource, Long> {

    @Autowired
    private ResourceService resourceService;

    @RequestMapping(value = "", method = RequestMethod.POST)
    @ResponseBody
    public Response<Resource> create(Resource resource) {
        if (resource == null || resource.getParentId() == null) {
            return new Response<Resource>(1001, "创建失败，参数不合法");
        }
        Resource parent = resourceService.findOne(resource.getParentId());

        resource.setParentIds(parent.getParentIds() + parent.getId() + "/");
        resourceService.save(resource);
        if (resource != null) {
            return new Response<Resource>(resource);
        }
        return new Response<Resource>(1001, "创建失败");
    }

    @RequestMapping(value = "/{id}/detailAndChildren", method = RequestMethod.GET)
    @ResponseBody
    public Response<Resource> detailAndChildren(@PathVariable Long id) {
        Resource resource = resourceService.findOne(id);
        Resource parent = new Resource();
        parent.setParentId(id);
        List<Resource> children = resourceService.findAll(parent);
        resource.setChildren(children);
        return new Response<Resource>(resource);
    }

    @RequestMapping(value = "tree", method = RequestMethod.GET)
    @ResponseBody
    public Response<List<Resource>> tree(Resource resource, Boolean async) {
        List<Resource> list;
        if (async) {    //异步
            list = resourceService.findChildren(resource);
        } else {
            list = resourceService.findAll(resource);
        }
        if (!CollectionUtils.isEmpty(list)) {
            return new Response<>(list);
        } else {
            return new Response<>();
        }
    }
}
